from datetime import timedelta

from django.db.models import F
from django.utils import timezone
from rest_framework.exceptions import ValidationError
from tenant_schemas.utils import schema_context

from apps.booking.types import BookingStatusChoices, AppointmentStatusChoices
from apps.users.models import Provider


def cancel_appointment(request, instance, booking):
    now = timezone.now()

    provider = request.user.provider
    if provider.cancelation_balance > 0:
        if now - instance.created_at > timedelta(hours=24):
            with schema_context('public'):
                Provider.objects \
                    .filter(id=request.user.id) \
                    .update(cancelation_balance=F('cancelation_balance') - 1)
        booking.status = BookingStatusChoices.CANCELED.value
        booking.save()
        instance.status = AppointmentStatusChoices.CANCELLED.value
        instance.save()
    else:
        raise ValidationError('You have used all of your cancellation credit for this month.')
